<template>
  <div class="app-container" style="min-height: calc(100vh - 60px - 40px - 20px)" :class="isDev?'isdev':'isdevNo'">
    <div v-if="!isDev" class="mainbox">
      <dt-table
        ref="table"
        v-loading="loading"
        :table-opts="tableOpts"
        :is-show-column="true"
        :is-column-search="false"
        :pagination-data="{
          total:total,
          queryParams:queryParams
        }"
        @pagination="getDataList"
        @searchChange="handleQuery"
        @searchReset="handleReset"
        @selection-change="handleSelectionChange"


      />
    </div>
    <formDataDrawer v-if="!isDev" ref="formDataDrawerRef" :form-json="formJson"
                    :form-id="queryParams.formId" @getDataList="getDataList" />
    <importDialog v-if="!isDev" ref="importDialogRef" />
    <devTableDesign ref="devTableDesignRef" v-if="isDev" :isDefaultMenu="isDefaultMenu"/>
  </div>
</template>
<script>
import { default as request, cloud } from '@/framework/utils/request'
import { getTableOptions } from '@/framework/views/developer-center/application-center/application-system/applicationFormDesign/build/generator/json-data'
import formDataDrawer from './components/formDataDrawer'
import { getList, getDesignerList, queryPageDesign, queryListDesign, customFormDataDelete, importUploadFile, downloadTemplate, exportFormData, customButtonOperate, exportDataValidation } from '@/framework/api/developerCenter/formDesignData'
import importDialog from './components/importDialog.vue'
import devTableDesign from './components/devTableDesign.vue'
import buttonConfigApi from '@/framework/api/developerCenter/application-system/buttonConfig'
import { slice } from '@/framework/mock/accountUnlocking'
import { getSysMenuDetail } from '@/framework/api/menu'
import { dateTimeFormat } from '@/framework/utils/dateTime'

export default {
  name: 'ApplicationSystem',
  components: {
    // formDataDialog,
    formDataDrawer,
    importDialog,
    devTableDesign
  },
  props: {
    isDev: {
      type: Boolean,
      default: false
    },
    isDefaultMenu: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 内置按钮
      btnObj: {
      // 新增
        add: {
          type: 'primary',
          click: () => {
            if (!this.formJson) {
              this.$dtMessage({
                message: '表单为空，暂不支持新增数据',
                type: 'error'
              })
              return
            }
            this.$refs.formDataDrawerRef.handleOpen('add')
          }
        },
        // 编辑
        edit: {
          click: (row) => {
            this.$refs.formDataDrawerRef.handleOpen('edit', row)
          }
        },
        // 详情
        detail: {
          click: (row) => {
            this.$refs.formDataDrawerRef.handleOpen('detail', row)
          }
        },
        // 批量删除
        batchdel: {
          click: () => {
            const that = this
            if (!that.multipleSelection || that.multipleSelection.length === 0) {
              this.$dtModal.msgError('请先选择要批量处理的数据')
              return
            }
            const ids = that.multipleSelection.map((res) => {
              return res.id
            })
            that.$dtModal.confirm('确认删除所选记录？删除后无法恢复').then(() => {
              const params = {
                formId: that.queryParams.formId,
                formDataIds: ids.join(',') // 接口id集合[]
              }
              return customFormDataDelete(params)
            }).then(() => {
              this.getDataList()
              this.$dtModal.msgSuccess('批量删除成功')
              that.$refs.table.clearSelection()
            }).catch(() => {})
          }
        },
        // 删除
        delete: {
          click: (row) => {
            this.$dtModal.confirm('确认删除此记录？删除后无法恢复').then(() => {
            // this.$dtModal.confirm(`确认删除${this.$route.query.appName}应用的业务数据吗？删除后无法恢复`).then(() => {
              return customFormDataDelete({ formDataIds: row.id, formId: this.queryParams.formId })
            }).then(() => {
              this.getDataList()
              this.$dtModal.msgSuccess('删除成功')
            }).catch(() => {})
          }
        },
        // 导入
        dataimport: {
          click: (row) => {
            this.params = { formId: this.queryParams.formId, formName: this.formName }
            this.$refs.importDialogRef.openImportDialog(this.params)
          }
        },
        // 导出
        dataexport: {
          click: (row) => {
            this.handleDownload(row)
          }
        }
      },
      // 自定义按钮 actionType  动作类型 1打开视图 2 3 执行动作
      customBtnObj: {
        1: {
          click: (value) => {
            console.log('===', value)
            getSysMenuDetail({ menuId: value.toMenuId }).then((res) => {
              console.log('res', res)
              res.data.statusFlag == 1 && this.$router.push({ path: this.$route.path, query: { ...this.$route.query, ...value, menuId: value.toMenuId, menuCode: value.toMenuCode, menuName: value.toMenuName, formId: value.toFormId } })
            })
          }
        },
        2: {
          click: (value) => {
            window.open(value.showUrl)
          }
        },
        3: {
          click: (value) => {
            if (value.carryData == 1 && !this.multipleSelection || this.multipleSelection.length === 0) {
              this.$dtModal.msgError('请先选择要批量处理的数据')
              return
            }
            const formDatas = this.multipleSelection.map((res) => {
              return res
            })
            this.$dtModal.confirm(`确认${value.label}${this.$route.query.appName}应用的业务数据吗？删除后无法恢复`).then(() => {
              const params = {
                formId: this.queryParams.formId,
                formDatas,
                buttonCode: value.buttonCode
              }
              return customButtonOperate(params)
            }).then(() => {
              this.getDataList()
              this.$dtModal.msgSuccess('操作成功')
              this.$refs.table.clearSelection()
            }).catch(() => {})
          }
        }
      },
      tableOpts: {},
      // 表单结构
      // formJson: { fields: [{ __config__: { label: '物品名称', labelWidth: null, showLabel: true, changeTag: true, tag: 'el-input', tagIcon: 'input', icon: 'Language', required: false, layout: 'colFormItem', span: 24, document: 'https://element.eleme.cn/#/zh-CN/component/input', regList: [], isFromTable: true, tableColumnType: 'input', formId: 101, renderKey: '1011698306291755' }, __slot__: { prepend: '', append: '' }, placeholder: '请输入物品名称', style: { width: '100%' }, clearable: true, 'prefix-icon': '', 'suffix-icon': '', maxlength: 30, 'show-word-limit': false, readonly: false, disabled: false, show: true, developerShow: true, search: true, tagType: 'text', isModelDisable: true, modelType: '字符串', __vModel__: 'field101' }, { __config__: { label: '规格型号', showLabel: true, labelWidth: null, tag: 'el-select', tagIcon: 'select', icon: 'arrow-down', layout: 'colFormItem', dataType: 'static', span: 24, required: false, regList: [], isFromTable: true, changeTag: true, document: 'https://element.eleme.cn/#/zh-CN/component/select', tableColumnType: 'select', method: 'get', formId: 102, renderKey: '1021698306310570', defaultValue: '1' }, __slot__: { options: [{ label: '大', value: '1' }, { label: '中', value: '2' }, { label: '小', value: '3' }] }, placeholder: '请选择规格型号', style: { width: '100%' }, clearable: true, disabled: false, show: true, developerShow: true, search: false, filterable: false, multiple: false, isModelDisable: true, modelType: '字符串', __vModel__: 'field102' }, { __config__: { label: '数量', showLabel: true, changeTag: true, labelWidth: null, tag: 'el-input-number', tagIcon: 'number', icon: 'timer', defaultValue: 0, span: 24, layout: 'colFormItem', required: false, isFromTable: true, regList: [], document: 'https://element.eleme.cn/#/zh-CN/component/input-number', tableColumnType: 'number', formId: 103, renderKey: '1031698306322471' }, placeholder: '数量', step: 1, 'step-strictly': false, 'controls-position': '', disabled: false, show: true, developerShow: true, search: false, tagType: 'number', isModelDisable: true, modelType: '数字', __vModel__: 'field103' }, { __config__: { label: '出场日期', tag: 'el-date-picker', tagIcon: 'date', icon: 'calendar', defaultValue: null, showLabel: true, labelWidth: null, span: 24, layout: 'colFormItem', required: false, regList: [], isFromTable: true, changeTag: true, document: 'https://element.eleme.cn/#/zh-CN/component/date-picker', tableColumnType: 'date', formId: 106, renderKey: '1061698306543557' }, isDefaultValueShow: false, placeholder: '请选择出场日期', type: 'date', style: { width: '100%' }, disabled: false, show: true, developerShow: true, search: false, clearable: true, format: 'yyyy-MM-dd', 'value-format': 'yyyy-MM-dd', readonly: false, tagType: 'date', isModelDisable: true, modelType: '日期', __vModel__: 'field106' }, { __config__: { label: '物品简介', labelWidth: null, showLabel: true, tag: 'el-input', tagIcon: 'textarea', icon: 'tickets', required: false, layout: 'colFormItem', span: 24, regList: [], changeTag: true, isFromTable: true, document: 'https://element.eleme.cn/#/zh-CN/component/input', tableColumnType: 'textarea', formId: 105, renderKey: '1051698306355198' }, type: 'textarea', placeholder: '请输入物品简介', autosize: { minRows: 4, maxRows: 4 }, style: { width: '100%' }, maxlength: 30, 'show-word-limit': false, readonly: false, disabled: false, show: true, developerShow: false, search: true, tagType: 'text', isModelDisable: true, modelType: '字符串', __vModel__: 'field105' }], formRef: '采购信息', tableCode: 'cf_jls0jo9k', formModel: 'formData', size: 'medium', labelPosition: 'right', labelWidth: 100, formRules: 'rules', gutter: 0, disabled: false, span: 24, formBtns: true },
      formJson: {},
      formName: '',
      total: 0,
      loading: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        formId: '',
        configPagination: '1'
      },
      multipleSelection: [],
      btnlist: [
        {
          label: '新增',
          buttonCode: 'add',
          status: 1, // 0不显示 1显示
          location: 1, // 1 上边，  2 操作列
          buttonType: 0 // 内置buttonType=0，新增的按钮都是自定义按钮buttonType=1
        },
        {
          label: '批量删除',
          buttonCode: 'batchDel',
          status: 1,
          location: 1, // 1 上边
          buttonType: 0
        },
        {
          label: '导入2',
          buttonCode: 'dataImport',
          status: 1,
          location: 1, // 2 操作列
          buttonType: 0
        },
        {
          label: '导出1',
          buttonCode: 'dataExport',
          status: 1,
          location: 1, // 1 上边
          buttonType: 0
        },
        {
          text: '编辑',
          buttonCode: 'edit',
          status: 1,
          location: 2, // 2 操作列
          buttonType: 0
        },
        {
          text: '详情',
          buttonCode: 'detail',
          status: 1,
          location: 2, // 2 操作列
          buttonType: 0
        },
        {
          text: '删除',
          buttonCode: 'delete',
          status: 1,
          location: 2, // 1 上边
          buttonType: 0
        },
        {
          label: '内置按钮1',
          buttonCode: 'neizhi',
          status: 1,
          location: 1, // 1 上边
          buttonType: 1,
          actionType: 1
        },
        {
          label: '内置按钮2',
          buttonCode: 'nz',
          status: 1,
          location: 1, // 1 上边
          buttonType: 1,
          actionType: 2
        }
      ],
      list: [],
      isHaveFlow: false,
      flowCol: [],
      defaultCol: []
    }
  },
  watch: {
    $route: {
      handler(newVal) {
        this.queryParams.formId = newVal.query.formId
        this.loading = true
        this.formJson = {}
        if (!this.isDev) { // 用户访问
          this.getFormJson()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.queryParams.formId = this.$route.query.formId
  },
  methods: {
    // 1 获取formjson
    getFormJson() {
      // queryPageDesign({ formId: this.queryParams.formId }).then((res) => {
      queryListDesign({ formId: this.queryParams.formId }).then((res) => {
        this.formJson = JSON.parse(res.data.formContent)
        const menuType = res.data && res.data.formCode ? res.data.formCode.slice(0, -9) : ''
        this.formName = res.data.formName
        this.isHaveFlow = res.data.bind === 1
        this.flowCol = res.data.flowContent ? JSON.parse(res.data.flowContent) : []
        // this.defaultCol = res.data.defaultColumnContent ? JSON.parse(res.data.defaultColumnContent) : []
        // 2.获取按钮列表 ，将显示按钮处理成table所需的两类 toolbarBtn operatorBtn
        if (!this.isDefaultMenu) { // 除了流程那块的菜单
          this.getBtnList()
        } else {
          // 流程那边的菜单，需要的按钮不同,只需要一个详情按钮，点击跳转到流程详情页面
          this.operatorBtn = [{
            text: menuType == 'myTodo' ? '处理' : '详情',
            buttonCode: 'detail',
            status: 1,
            location: 2, // 2 操作列
            buttonType: 0,
            click: (row) => {
              if (this.$route.query.menuCode.substr(0, this.$route.query.menuCode.length - 6) === 'systemLog') {
                this.$refs.formDataDrawerRef.handleOpen('detail', row)
                return
              }
              const path = this.$route.path === '/home/visitorTemplate' ? '/home/lowCodeFlowDetail' : '/lowCodeFlowDetail'
              const query = {
                'myApply': () => {
                  return {
                    id: row.id, // 流程实例id
                    type: 'applied', // 流程状态-已发申请
                    row// 流程对应的数据
                  }
                },
                'myTodo': () => {
                  return {
                    row,
                    taskId: row.id, // 待办任务的id
                    id: row.instanceId, // 流程实例id
                    type: 'needtodo'// 流程类型-待办
                  }
                },
                'myDone': () => {
                  return {
                    taskId: row.id, // 已办任务的id
                    id: row.instanceId, // 流程实例id
                    type: 'doneTask', // 流程状态-已办
                    row // 流程数据
                  }
                },
                'myCopy': () => {
                  return {
                    csId: row.id, // 抄送id
                    procdefId: row.procdefId, // 流程定义id
                    id: row.instanceId, // 流程实例id
                    nodeId: row.nodeId, // 流程结点id
                    type: 'cs', // 流程状态-抄送事宜
                    row
                  }
                }
              }
              const queryParams = function (menuType) {
                return query[menuType]()
              }
              this.$router.push({
                path,
                query: queryParams(menuType)
              })
            }
          }]
          this.getTable(this.formJson, [], this.operatorBtn)
        }
      })
    },
    // 2.获取按钮列表
    getBtnList() {
      buttonConfigApi.getLowCodeButtonList({ formId: this.queryParams.formId }).then((res) => {
        this.btnlist = res.data
        this.getTableBtn(this.btnlist)
      })
      // this.getTableBtn(this.btnlist)
    },
    getTableBtn(btnlist) {
      const btnlistShow = btnlist.filter((item) => {
        return item.status === 1 // 从所有按钮中筛选要显示的按钮
      })
      this.toolbarBtn = [] // 要展示在上方的按钮
      this.operatorBtn = [] // 要展示在操作列的按钮
      btnlistShow.forEach((item, index) => {
        // 内置按钮
        if (item.buttonType === 0) { // 内置buttonType=0
          item = { ...item, ...this.btnObj[item.buttonCode.slice(0, -9)] }
          // 位置location=1左上角
          item.location === 1 && item.label !== '列表' && this.toolbarBtn.push(item)
          // 位置location=2操作列
          item.location === 2 && this.operatorBtn.push(item)
        } else {
          // 自定义buttonType=1， 按钮都放操作列
          // actionType  动作类型 1打开视图 2 执行动作
          item = { ...item, ...this.customBtnObj[item.actionType] }
          this.toolbarBtn.push(item)
        }
      })
      this.getTable(this.formJson, this.toolbarBtn, this.operatorBtn)
    },
    getTable(formJson, toolbarBtn, operatorBtn) {
      // json to form
      this.tableOpts = getTableOptions(formJson, toolbarBtn, operatorBtn)
      // this.tableOpts.tableCol = [...this.tableOpts.tableCol, ...this.defaultCol]
      // 渲染出流程节点状态两个字段到table中
      if (this.isHaveFlow) {
        this.tableOpts.tableCol = [...this.tableOpts.tableCol, ...this.flowCol]
      }
      // 3.获取table数据
      this.getDataList()
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        formId: this.queryParams.formId,
        configPagination: '1'
      }
      this.handleQuery()
    },
    // 搜索
    handleQuery(formModel) {
      Object.keys(formModel || {}).forEach((key) => {
        if (Array.isArray(formModel[key])) {
          formModel[key] = formModel[key].join(',')
        }
      })
      // this.queryParams.formId = '1717447157864591361'
      this.queryParams = Object.assign(this.queryParams, { searchParams: formModel })
      this.queryParams.pageNo = 1
      this.$refs['table'].clearSelection()
      this.getDataList()
    },
    // 获取表格列表的业务数据
    getDataList() {
      const listApi = this.$route.path === '/home/visitorTemplate' ? getList : getDesignerList
      listApi(this.queryParams).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
        this.$nextTick(() => {
          this.$refs.table.$refs.table.doLayout()
        })
      })
    },
    clearSelection() {
      this.$refs['table'].clearSelection()
    },
    handleButtonConfig() {
      this.$refs.buttonConfigRef.openDrawer()
    },
    handlePluginConfig() {
      this.$refs.pluginConfigRef.openDrawer()
    },
    // 导出
    handleDownload() {
      // if (!this.multipleSelection || this.multipleSelection.length === 0) {
      //   this.$dtMessage({
      //     title: '失败',
      //     message: '请至少选择一项',
      //     type: 'error',
      //     duration: 2000
      //   })
      //   return
      // }
      const ids = (this.multipleSelection || []).map((res) => {
        return res.id
      }).join(',')
      this.showScreenLoading()
      exportDataValidation({ ids }, this.queryParams.formId).then((res) => {
        this.exportFormData(ids)
      }).catch((res) => {
        this.hideScreenLoading()
      })
    },
    exportFormData(ids) {
      exportFormData({ ids }, this.queryParams.formId).then((res) => {
        console.log('res', res)
        if (this.tableOpts.tableData == null) {
          this.$dtMessage({
            title: '失败',
            message: res.message,
            type: 'error',
            duration: 2000
          })
        } else {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          const fileType = res.headers['content-disposition'].substring(res.headers['content-disposition'].lastIndexOf('.') + 1).toLowerCase()
          const nowDateTime = dateTimeFormat()
          a.download = `${this.formName}导出信息${nowDateTime}.${fileType}` // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }
      }).catch((res) => {
        console.log('catch')
        this.hideScreenLoading()
      })
    }
  }
}
</script>
<style scoped lang="scss" >
.isdevNo{
  // margin-top: 40px;
}
.setbox{
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background: #fff;
  >span{
    margin-right: 16px;
  }
}
.el-button--text{
    color: #333;
  }
  .el-button--text:hover{
    color:var(--themeColor);
  }

</style>
